// axios基础的封装
import 'element-plus/theme-chalk/el-message.css'
import { ElMessage } from "element-plus"
import axios from "axios";
import router from "@/router/router.js";
import {useAdminStore} from "@/stores/index.js";

const adminRequest = axios.create({
    baseURL: 'http://localhost:10010',
    timeout: 5000
})

// axios请求拦截器
adminRequest.interceptors.request.use(config => {
    // 1. 从pinia获取token数据
    const adminStore = useAdminStore()
    // 2. 按照后端的要求拼接token数据
    const token = adminStore.token
    if (token) {
        config.headers.Authorization = token
    }
    return config
}, e => Promise.reject(e))

// axios响应式拦截器
adminRequest.interceptors.response.use(res => {
    // 未登录
    if (res.data.code === 0 && res.data.msg === '账号未登录') {
        const adminStore = useAdminStore()
        adminStore.removeToken()
        adminStore.clearAdminInfo()
        router.push('/admin/login')
    } else if ( res.data.code === 0) {
        ElMessage({
            type: 'warning',
            message: res.data.msg
        })
    } else {
        return res.data
    }
}, e => {
    // 统一错误提示
    ElMessage({
        type: 'warning',
        message: e.response.data.message
    })
    return Promise.reject(e)
})

export default adminRequest
